package com.xuecheng.content.services.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XCPlusException;
import com.xuecheng.base.utils.StringUtil;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachPlanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.services.mapper.CourseBaseMapper;
import com.xuecheng.content.services.mapper.CourseMarketMapper;
import com.xuecheng.content.services.mapper.CoursePublishMapper;
import com.xuecheng.content.services.mapper.CoursePublishPreMapper;
import com.xuecheng.content.services.service.CourseBaseInfoService;
import com.xuecheng.content.services.service.CourseMarketService;
import com.xuecheng.content.services.service.CoursePublishService;
import com.xuecheng.content.services.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:王亚栋
 * @Date:2023/8/6 17:29
 * @Version:1.0
 */
@Service
@Slf4j(topic = "CoursePublishServiceImpl")
public class CoursePublishServiceImpl implements CoursePublishService {


    @Autowired
    private CourseBaseInfoService courseBaseInfoService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    /**
     * Mq 消息服务
     */
    @Resource
    private MqMessageService mqMessageService;

    /**
     *  预览课程信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();

        // 课程基本信息，营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);

        // 课程计划信息
        List<TeachPlanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);

        coursePreviewDto.setTeachplans(teachPlanTree);
        coursePreviewDto.setCourseBase(courseBaseInfo);

        return coursePreviewDto;
    }

    /**
     * 提交审核
     * @param companyId 机构Id
     * @param courseId  课程Id
     */
    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {

        //先查询出课程
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);

        if (courseBaseInfo == null){

            XCPlusException.cast("课程信息找不到!");
        }
        //课程的审核状态
        String auditStatus = courseBaseInfo.getAuditStatus();

        //如果课程的审核状态为已提交则不允许提交
        if (auditStatus.equals("202003")){

            XCPlusException.cast("课程已提交，请等待审核！");
        }

        //课程的图片，计划信息没有填写也不运行提交
        String pic = courseBaseInfo.getPic();

        if (StringUtil.isEmpty(pic)){

            XCPlusException.cast("上传课程的图片不能为空！");
        }

        //查询出课程计划
        List<TeachPlanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);

        if (teachPlanTree == null || teachPlanTree.size() == 0){

            XCPlusException.cast("请编写课程计划！");
        }
        //TODO 本机构只能审核属于本机构的课程信息

        //查询到课程基本信息，营销信息，计划等信息插入到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();

        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);

        // 设置机构Id
        coursePublishPre.setCompanyId(companyId);

        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        //转为json
        String courseMarketJSON = JSON.toJSONString(courseMarket);

        coursePublishPre.setMarket(courseMarketJSON);

        //计划信息 转json
        String teachPlanJson = JSON.toJSONString(teachPlanTree);

        coursePublishPre.setTeachplan(teachPlanJson);

        //改变状态为已提交
        coursePublishPre.setStatus("202003");

        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());

        //查询预发布表，如果有更新记录；没有则插入数据
        CoursePublishPre coursePublishPre1 = coursePublishPreMapper.selectById(courseId);

        if (coursePublishPre1 == null){

            coursePublishPreMapper.insert(coursePublishPre);
        }else {

            //更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseMapper.selectById(courseId);

        //设置审核状态为已提交
        courseBase.setAuditStatus("202003");

        courseBaseMapper.updateById(courseBase);

    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {

        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);

        return coursePublish;
    }

    /**
     * 课程发布功能
     * @param companyId 机构Id
     * @param courseId  课程Id
     */
    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {

        //1.查询预发布表信息
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);

        if (coursePublishPre == null) {

            XCPlusException.cast("课程没有审核记录，无法进行发布！");
        }
        //校验
        //没有审核通过，不允许发布
        String status = coursePublishPre.getStatus();

        if (!status.equals("202004")){

            XCPlusException.cast("课程没有通过审核，不允许发布！");
        }

        //2.向课程发布表写记录
        CoursePublish coursePublish = new CoursePublish();

        BeanUtils.copyProperties(coursePublishPre,coursePublish);

        //TODO 先查询课程发布表--如果有则更新，没有则添加
        CoursePublish coursePublish1 = coursePublishMapper.selectById(courseId);

        if (coursePublish1 == null){

            //插入数据
            coursePublishMapper.insert(coursePublish);
        }else {

            //更新数据
            coursePublishMapper.updateById(coursePublish);
        }


        //3.向消息表写入数据
        saveCoursePublishMessage(courseId);

        //4.将预发布表数据删除
        int deleteResult = coursePublishPreMapper.deleteById(courseId);
        log.info("课程发布功能 -- 预发布表数据删除:{}",deleteResult);


    }

    /**
     * 保存消息记录表
     * @param courseId 课程Id
     */
    private void saveCoursePublishMessage(Long courseId) {

        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);

        if (mqMessage == null){

            XCPlusException.cast(CommonError.UN_KNOW_ERROR);
        }

    }
}
